﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SovaWebService
{
    public static class UrlHelper
    {
        public static string CurrentPageUrl(IUrlHelper url, string action, int page, int pageSize) {
            return url.Link(action, new { page, pageSize });
        }
        public static string FirstPageUrl(IUrlHelper url, string action, int pageSize) {
            return url.Link(action, new { page = 0, pageSize });
        }

        public static string PreviousPageUrl(IUrlHelper url, string action, int page, int pageSize)
        {
            if (page <= 0)
            {
                return null;
            }

            return url.Link(action, new { page = page - 1, pageSize });
        }

        public static string NextPageUrl(IUrlHelper url, string action, int page, int pageSize, int itemsCount)
        {
            int maxPages = (int) Math.Floor((double) itemsCount / pageSize);

            if (page >= maxPages || page < 0)
            {
                return null;
            }

            return url.Link(action, new { page = page + 1, pageSize });
        }

        public static string LastPageUrl(IUrlHelper url, string action, int pageSize, int itemsCount) {
            int lastPage = (int) Math.Floor((double) itemsCount / pageSize);
            return url.Link(action, new { page = lastPage, pageSize });
        }

        /**
         * Returns a dynamic object only with Pagination.
         * @see https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/operator#example
         */
        public static dynamic Pagination(IUrlHelper url, string action, int page, int pageSize, int itemsCount) {
            
            return new {
                CurrentPageUrl = CurrentPageUrl(url, action, page, pageSize),
                FirstPageUrl = FirstPageUrl(url, action, pageSize),
                PreviousPageUrl = PreviousPageUrl(url, action, page, pageSize),
                NextPageUrl = NextPageUrl(url, action, page, pageSize, itemsCount),
                LastPageUrl = LastPageUrl(url, action, pageSize, itemsCount),
            };
        }
    }
}
